define [
	'jquery'
	'sammy/plugins/sammy.template-0.7.1.min.js'
	'jquery.couch.js'
	'helper'
], ($, undef, undef, H) ->
	S = {}
	$.fn.mb_donation_detail = (SamCtx) ->
	
		# Global variable
		$this = $(@)
		S = SamCtx
		
		# Initialization and table creation
		unless @mb_plugin()
			@mb_plugin 'donation_detail'
			$this.find('h3').after("
							<table>
								<tbody>
								</tbody>
							</table>
							<hr>
							")

			$tpl = $('<tr>').html '
						<td>
							<%= property %>
						</td>
						<td>
							<%= value %>
						</td>'

		
			# Main subscription event to handle published donation id and display it in the current page
			$.subscribe "mb.donation", (e, arg) =>

				_dnID = arg['id']
				
				# Empty the table
				$this.find('tbody').empty()
			
				# Open couch document for reading
				$.couch.db("vcn-members").openDoc _dnID, {
					success: (doc) ->
						# Iterate through all couch doc properties
						for i of doc
							_omit = ['old_id', 'type', '_id', '_rev']
							continue if i.matches(_omit)
							if i is "cash"
								x = "Cash"
								if eval(doc[i]) then doc[i] = "Yes" else doc[i] = "No"
							doc[i] = "$#{doc[i]}.00" if i is "donation_amount"
							x = i.replace(/_/g, " ").toCaps()
							content = S.content $tpl,
								property: x
								value: doc[i]
							$this.find('tbody')
									.append $('<tr>').append content

					}

				# Define click event handling for Print Receipt button
				$this.find('[name="view_receipt"]').on 'click', ->
					S.app.setLocation "#/view_receipt"
					
				return
		return @
	return
